<template>
  <div class="result-page">
    <van-nav-bar title="考试结果" left-arrow @click-left="onClickLeft" />

    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" />
    </div>

    <template v-else-if="examResult">
      <div class="content-container">
        <!-- 得分卡片 -->
        <div class="score-card">
          <div class="score-value">{{ examResult.score }}</div>
          <div class="score-total">总分: {{ examResult.total_score }}</div>
          <div class="score-label">
            {{ getScoreLevel(examResult.score, examResult.total_score) }}
          </div>
        </div>

        <!-- 统计数据 -->
        <div class="stats-card">
          <div class="stat-item">
            <div class="stat-value">{{ examResult.correct_count }}</div>
            <div class="stat-label">答对题目</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ examResult.wrong_count }}</div>
            <div class="stat-label">答错题目</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">{{ examResult.unanswered_count }}</div>
            <div class="stat-label">未作答</div>
          </div>
          <div class="stat-item">
            <div class="stat-value">
              {{ formatDuration(examResult.duration) }}
            </div>
            <div class="stat-label">用时</div>
          </div>
          <div class="stat-item" v-if="examResult.rank">
            <div class="stat-value rank-value">{{ examResult.rank }}</div>
            <div class="stat-label">排名</div>
          </div>
        </div>

        <!-- 考试信息 -->
        <div class="exam-info-card">
          <div class="card-title">考试信息</div>
          <div class="info-row">
            <div class="info-label">考试名称:</div>
            <div class="info-value">{{ examResult.exam_name }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">开始时间:</div>
            <div class="info-value">
              {{ formatDateTime(examResult.start_time) }}
            </div>
          </div>
          <div class="info-row">
            <div class="info-label">提交时间:</div>
            <div class="info-value">
              {{ formatDateTime(examResult.submit_time) }}
            </div>
          </div>
          <div class="info-row">
            <div class="info-label">试卷名称:</div>
            <div class="info-value">{{ examResult.paper_name }}</div>
          </div>
          <div class="info-row">
            <div class="info-label">题目数量:</div>
            <div class="info-value">{{ examResult.question_count }}题</div>
          </div>
        </div>

        <!-- 题型统计 -->
        <div class="question-types-card" v-if="examResult.type_stats">
          <div class="card-title">题型统计</div>
          <div class="type-stats">
            <div
              class="type-item"
              v-for="(stat, type) in examResult.type_stats"
              :key="type"
            >
              <div class="type-name">{{ getQuestionTypeName(type) }}</div>
              <div class="type-accuracy">
                正确率:
                {{
                  Math.round(
                    (stat.correct_count /
                      (stat.correct_count + stat.wrong_count)) *
                      100
                  ) || 0
                }}%
              </div>
              <div class="type-progress">
                <div
                  class="progress-bar"
                  :style="{
                    width: `${
                      Math.round(
                        (stat.correct_count /
                          (stat.correct_count + stat.wrong_count)) *
                          100
                      ) || 0
                    }%`,
                  }"
                ></div>
              </div>
              <div class="type-count">
                {{ stat.correct_count }}/{{
                  stat.correct_count + stat.wrong_count
                }}
              </div>
            </div>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
          <van-button type="primary" block @click="viewDetail">
            查看详细答题情况
          </van-button>
          <van-button
            plain
            type="primary"
            block
            @click="viewRanking"
            style="margin-top: 12px"
          >
            查看排名
          </van-button>
          <van-button
            plain
            type="default"
            block
            @click="goToHome"
            style="margin-top: 12px"
          >
            返回首页
          </van-button>
        </div>
      </div>
    </template>

    <div v-else class="empty-state">
      <van-empty description="未找到考试结果" />
    </div>
  </div>
</template>

<script setup lang="ts">
import {
  onMounted,
  ref,
} from 'vue';

import { showToast } from 'vant';
import {
  useRoute,
  useRouter,
} from 'vue-router';

import { examApi } from '../../api/modules/exam';

const router = useRouter();
const route = useRoute();

const loading = ref(true);
const examResult = ref<any>(null);

// 获取考试结果
onMounted(async () => {
  const recordId = route.params.id as string;
  if (!recordId) {
    showToast("未找到考试记录ID");
    router.replace("/home");
    return;
  }

  try {
    const response = await examApi.getExamResult(recordId);
    const rawData = response.data;

    // 处理后端返回的数据，计算分数和统计信息
    const processedData = processExamResult(rawData);
    examResult.value = processedData;

    console.log("考试结果数据:", {
      raw: rawData,
      processed: processedData,
    });
  } catch (error) {
    console.error("获取考试结果失败", error);
    showToast("获取考试结果失败");
  } finally {
    loading.value = false;
  }
});

// 处理考试结果数据
const processExamResult = (data: any) => {
  // 新的数据结构已经包含了计算好的分数和统计信息
  if (data.user_score !== undefined && data.total_score !== undefined) {
    return {
      ...data,
      score: data.user_score,
      total_score: data.total_score,
      correct_count: data.correct_count || 0,
      wrong_count: data.wrong_count || 0,
      unanswered_count: data.unanswered_count || 0,
      exam_name: data.exam_id?.exam_name || "未知考试",
      question_count: data.answers?.length || 0,
      duration: calculateDuration(data.start_time, data.submit_time),
    };
  }

  // 兼容旧数据结构的处理逻辑（保留原来的计算逻辑作为后备）
  const answers = data.answers || [];
  let totalScore = 0;
  let userScore = 0;
  let correctCount = 0;
  let wrongCount = 0;
  let unansweredCount = 0;

  // 计算分数和统计信息
  answers.forEach((answer: any) => {
    if (answer.question_snapshot) {
      // 新格式：使用快照数据
      const questionScore = answer.question_snapshot.score || 0;
      totalScore += questionScore;
      userScore += answer.earned_score || 0;

      if (answer.selected_answers?.length === 0) {
        unansweredCount++;
      } else if (answer.is_correct) {
        correctCount++;
      } else {
        wrongCount++;
      }
    } else {
      // 旧格式：需要关联查询（已废弃，但保留兼容性）
      const question = answer.question_id;
      const userAnswers = answer.selected_answers || [];
      const correctAnswers = question?.answer || [];
      const questionScore = question?.score || 0;

      totalScore += questionScore;

      if (userAnswers.length === 0) {
        unansweredCount++;
      } else {
        const isCorrect = arraysEqual(
          userAnswers.sort(),
          correctAnswers.sort()
        );
        if (isCorrect) {
          correctCount++;
          userScore += questionScore;
        } else {
          wrongCount++;
        }
      }
    }
  });

  return {
    ...data,
    score: userScore,
    total_score: totalScore,
    correct_count: correctCount,
    wrong_count: wrongCount,
    unanswered_count: unansweredCount,
    duration: calculateDuration(data.start_time, data.submit_time),
    exam_name: data.exam_id?.exam_name || "未知考试",
    question_count: answers.length,
  };
};

// 计算考试用时
const calculateDuration = (startTime: string, submitTime: string) => {
  if (!startTime || !submitTime) return 0;
  const start = new Date(startTime).getTime();
  const submit = new Date(submitTime).getTime();
  return Math.floor((submit - start) / 1000);
};

// 判断两个数组是否相等
const arraysEqual = (a: number[], b: number[]) => {
  if (a.length !== b.length) return false;
  return a.every((val, index) => val === b[index]);
};

// 获取成绩等级
const getScoreLevel = (score: number, totalScore: number) => {
  const percentage = (score / totalScore) * 100;

  if (percentage >= 90) {
    return "优秀";
  } else if (percentage >= 80) {
    return "良好";
  } else if (percentage >= 60) {
    return "及格";
  } else {
    return "不及格";
  }
};

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  const date = new Date(dateStr);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");
  const hours = String(date.getHours()).padStart(2, "0");
  const minutes = String(date.getMinutes()).padStart(2, "0");

  return `${year}-${month}-${day} ${hours}:${minutes}`;
};

// 格式化考试用时
const formatDuration = (seconds: number) => {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);
  const secs = seconds % 60;

  if (hours > 0) {
    return `${hours}小时${minutes}分钟`;
  } else {
    return `${minutes}分钟${secs}秒`;
  }
};

// 获取题型名称
const getQuestionTypeName = (type: string) => {
  switch (type) {
    case "Judgement":
      return "判断题";
    case "Select":
      return "单选题";
    case "multiSelect":
      return "多选题";
    default:
      return type;
  }
};

// 查看详细答题情况
const viewDetail = () => {
  // 跳转到详细页面 (实际项目中可能需要实现)
  showToast("暂未实现详细查看功能");
};

// 查看排名
const viewRanking = () => {
  // 尝试获取考试ID，考虑不同的数据结构
  let examId = null;

  if (examResult.value?.exam_id) {
    // 如果exam_id是字符串，直接使用
    if (typeof examResult.value.exam_id === "string") {
      examId = examResult.value.exam_id;
    }
    // 如果exam_id是对象，获取其_id字段
    else if (
      typeof examResult.value.exam_id === "object" &&
      examResult.value.exam_id._id
    ) {
      examId = examResult.value.exam_id._id;
    }
  }

  if (!examId) {
    showToast("无法获取考试信息");
    return;
  }

  console.log("跳转到排名页面，examId:", examId);
  router.push(`/exam/${examId}/ranking`);
};

// 返回首页
const goToHome = () => {
  router.replace("/home");
};

// 返回上一页
const onClickLeft = () => {
  router.back();
};
</script>

<style scoped>
.result-page {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.content-container {
  padding: 16px;
}

.score-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 24px 16px;
  text-align: center;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.score-value {
  font-size: 48px;
  font-weight: 700;
  color: #1989fa;
  line-height: 1.2;
}

.score-total {
  font-size: 16px;
  color: #969799;
  margin-bottom: 8px;
}

.score-label {
  font-size: 18px;
  font-weight: 500;
  color: #07c160;
}

.stats-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.stat-item {
  text-align: center;
  flex: 1;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #323233;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #969799;
}

.exam-info-card,
.question-types-card {
  background-color: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #323233;
}

.info-row {
  display: flex;
  margin-bottom: 8px;
  font-size: 14px;
}

.info-label {
  width: 80px;
  color: #969799;
}

.info-value {
  flex: 1;
  color: #323233;
}

.type-stats {
  margin-top: 12px;
}

.type-item {
  margin-bottom: 16px;
}

.type-name {
  font-size: 14px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 4px;
}

.type-accuracy {
  font-size: 12px;
  color: #969799;
  margin-bottom: 4px;
}

.type-progress {
  height: 6px;
  background-color: #f2f3f5;
  border-radius: 3px;
  overflow: hidden;
  margin-bottom: 4px;
}

.progress-bar {
  height: 100%;
  background-color: #1989fa;
  border-radius: 3px;
}

.type-count {
  font-size: 12px;
  color: #969799;
  text-align: right;
}

.action-buttons {
  margin-top: 24px;
  margin-bottom: 32px;
}

.rank-value {
  color: #ff976a !important;
  font-weight: 600;
}

.loading-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
}
</style>
